package com.atlige.gzmallssoserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author: Jeremy lI
 * @description:
 * @date: created in 2021/6/5 11:27
 */
@Controller
@Slf4j
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam(value = "token") String token) {
        String s = redisTemplate.opsForValue().get(token);
        return s;

    }


    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url,
                            @CookieValue(value = "ssoToken", required = false) String ssoToken,
                            Model model) {
        if (!StringUtils.isEmpty(ssoToken)) {
            return "redirect:" + url + "?token=" + ssoToken;
        }
        model.addAttribute("url", url);
        return "login";
    }

    @PostMapping(value = "/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("redirect_url") String url,
                          HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            //登录成功跳转，跳回到登录页
            String token = UUID.randomUUID().toString().replace("-", "");
            Cookie ssoToken = new Cookie("ssoToken", token);
            redisTemplate.opsForValue().set(token, username);
            response.addCookie(ssoToken);
            return "redirect:" + url + "?token=" + token;
        }
        return "login";
    }
}
